/**
 * Created by aifece on 15/1/19.
 */
(function(){
  function AddressJs(option){
    var _this = this;

    this._default = {
      'receiver' : ".js_ADDReceiver",
      'address'  : '.js_ADDAddress',
      'mobile'   : '.js_ADDMobile',
      'tel'      : '.js_ADDTel',
      'province' : '#pre_province',
      'city'     : '#pre_city',
      'district' : '#pre_district',
      'sltprov'  : '#prov',
      'sltcity'  : '#city',
      'sltdist'  : '#dist',
      'isDef'    : '.js_ADDIsDefault',
      'add'      : '.js_addressAdd',
      'edit'     : '.js_addressEdit',
      'modify'   : '.js_modifyAddress',
      'save'     : '.js_ADDSave',
      'input'    : '.js_sltAddressInp',
      'formDiv'  : '.js_addressForm',
      'infoDiv'  : '.js_addressInfo',
      'parentDiv': '.js_addressParent',
      'listDiv'  : '.js_addressList',
      'addressOpt': '#addressPro',
      'paydiv'    : '.js_tmpPayDiv',
      'sltPayDiv' : '.js_tmpSltDiv'
    };

    this.option = $.extend(this._default, option);

    this.option.addressSlt = new AjaxAddress({
      'url'          : siteUrl+'/provincial/get_provincial',
      'parentEle'    : '#addressSlt',
      'province'     : '#prov',
      'city'         : '#city',
      'district'     : '#dist',
      'prov_title'   : '省/直辖市',
      'city_title'   : '市',
      'dist_title'   : '区/县',
      'default_prov' : $(_this.option.province).val(),
      'default_city' : $(_this.option.city).val(),
      'default_dist' : $(_this.option.district).val()
    });

    $('body').on('click', this.option.edit, function(e){
      e.stopPropagation();
      _this.setForm($(this));
    });
    $('body').on('click', this.option.edit+' span', function(e){
      e.stopPropagation();
      _this.setForm($(this));
    });

    $(this.option.add).on('click', function(){
      _this.setForm($(this));
    });

    // 修改地址
    $(this.option.modify).on('click', function(){
      _this.showForm();
    });

    // 激活表单 取消错误提示
    $(this.option.formDiv+' input').on('focus', function () {
      _this.deleteMsg($(this));
    });

    // 离开表单 激活提示信息
    $(this.option.receiver).on('blur', function () {
      var value = $(this).val();
      if (value.length >= 2 && value.length <= 15) {
        return;
      }

      var msg = '请输入收货人姓名';
      if (value.length < 2 || value.length > 15) {
        msg = '收货人姓名不能少于2位，大于15位';
      }

      _this.inputMsg($(this), msg);
    });

    $(this.option.address).on('blur', function () {
      var value = $(this).val();
      if (value.length > 2) {
        return;
      }

      _this.inputMsg($(this), '请输入收货人详细地址');
    });

    $(this.option.mobile).on('blur', function () {
      var value = $(this).val();
      if (!value || (value.length == 11 && value.match(/^1[3456789][0-9]{9}$/))) {
        return;
      }

      if (value) {
        _this.inputMsg($(this), '手机号码格式不正确');
      }
    });

    $(this.option.tel).on('blur', function () {
      var value = $(this).val();
      if (!value || (value.length > 6 && value.match(/^[0-9\-]+$/))) {
        return;
      }

      if (value) {
        _this.inputMsg($(this), '座机号码格式不正确');
      }
    });

    // 添加新地址
    $(this.option.save).on('click', function () {
      var type = $(_this.option.input).val();
      if (!type) {
        type = 'new';
      }
      if ($(_this.option.save).data('saving') == 1) {
        return;
      }
      $(_this.option.save).data('saving', 0);
      _this.saveInfo(type);
    });
  }

  AddressJs.prototype.extendSave = function()
  {

  }

  AddressJs.prototype.setForm = function(obj)
  {
    var type = obj.data('type');
    var id = obj.attr('data-address_id');

    if (type == 'child') {
      obj.closest('ul').find('li').removeClass('curr');
      obj.closest('ul').find('.radio-bg').removeClass('checked');
      obj.closest('ul').find('input').attr('checked', false);

      obj.closest('li').addClass('curr');
      obj.closest('li').find('.radio-bg').addClass('checked');
      obj.closest('li').find('input').attr('checked', 'checked');
      $('.js_addressFormDiv').show();
    } else if (id == 'new') {
      $('.js_addressFormDiv').show();
      this.sltChange(obj);
    } else {
      $('.js_addressFormDiv').hide();
      this.sltChange(obj);
    }

    if (id == 'new') {
      this.showInfo(0, 'new');
    } else {
      this.showInfo(id, 'edit');
    }
  }

  AddressJs.prototype.showForm = function()
  {
    var _this = this;
    $(this.option.formDiv).find('input').each(function(){
      _this.deleteMsg($(this));
    });
    $(this.option.formDiv).removeClass('hidden');
    $(this.option.infoDiv).addClass('hidden');
    $(this.option.parentDiv).attr('data-edit-address', 1);
  }

  AddressJs.prototype.hideForm = function()
  {
    $(this.option.formDiv).addClass('hidden');
    $(this.option.infoDiv).removeClass('hidden');
    $(this.option.parentDiv).attr('data-edit-address', 0);
  }

  AddressJs.prototype.showInfo = function(id, type) {
    var _this = this;
    if (type == 'edit') {
      var url = siteUrl+'/address/get_address';
      $.post(url, {id:id},function(json){
        if (json.info == 'ok') {
          $(_this.option.receiver).val(json.address.receiver);
          $(_this.option.address).val(json.address.address);
          $(_this.option.mobile).val(json.address.mobile);
          $(_this.option.tel).val(json.address.tel);
          $(_this.option.province).val(json.address.province_id);
          $(_this.option.city).val(json.address.city_id);
          $(_this.option.district).val(json.address.district_id);
          if (json.address.is_default == 1) {
            $(_this.option.isDef).addClass('checked');
            $(_this.option.isDef).addClass('manager-on');
            $(_this.option.isDef).addClass('skin-check');
          } else {
            $(_this.option.isDef).removeClass('checked');
            $(_this.option.isDef).removeClass('manager-on');
            $(_this.option.isDef).removeClass('skin-check');
          }

          // 重设默认值
          _this.option.addressSlt.resetDefault(json.address.province_id, json.address.city_id, json.address.district_id);
        } else {
          showMsg(json.info);
        }
      }, 'json');
      $(this.option.input).val(id);
    } else {
      $(_this.option.receiver).val('');
      $(_this.option.address).val('');
      $(_this.option.mobile).val('');
      $(_this.option.tel).val('');
      $(_this.option.province).val('');
      $(_this.option.city).val('');
      $(_this.option.district).val('');
      $(_this.option.isDef).removeClass('checked manager-on skin-check');
      $(_this.option.input).val('new');

      // 重设默认值
      _this.option.addressSlt.resetDefault(0, 0, 0);
    }
  }

  AddressJs.prototype.sltChange = function(obj)
  {
    obj.closest('ul').find('li').removeClass('curr');
    obj.closest('ul').find('.radio-bg').removeClass('checked');
    obj.closest('ul').find('input').attr('checked', false);

    obj.addClass('curr');
    obj.find('.radio-bg').addClass('checked');
    obj.find('input').attr('checked', 'checked');
  }

  AddressJs.prototype.saveInfo = function (type) {
    var _this = this;
    var receiver = htmlSpecialChars($(_this.option.receiver).val());
    var address = htmlSpecialChars($(_this.option.address).val());
    var mobile = htmlSpecialChars($(_this.option.mobile).val());
    var tel = htmlSpecialChars($(_this.option.tel).val());
    var isDefault = 0;
    var prov = parseInt($(_this.option.sltprov).val());
    var city = parseInt($(_this.option.sltcity).val());
    var dist = parseInt($(_this.option.sltdist).val());


    if (!prov || prov == 0 || isNaN(prov)) {
      //showMsg('请选择省/直辖市');
      return;
    }
    if (!city || city == 0 || isNaN(prov)) {
      //showMsg('请选择市');
      return;
    }
    if (!dist || dist == 0 || isNaN(prov)) {
      //showMsg('请选择区/县');
      return;
    }

    var provT = $(_this.option.sltprov).find('option[value='+prov+']').html();
    var cityT = $(_this.option.sltcity).find('option[value='+city+']').html();
    var distT = $(_this.option.sltdist).find('option[value='+dist+']').html();

    if ($(_this.option.formDiv).find('.error').length > 0) {
      //showMsg('请输入正确的收货地址信息');
      return;
    }

    if (!address || !receiver){
      return;
    }
    if (!mobile && !tel) {
      //showMsg('手机号或座机号至少输入一个');
      _this.inputMsg($(this.option.mobile), '手机号或座机号至少输入一个');
      return;
    }

    if ($(_this.option.isDef).hasClass('checked') || $(_this.option.isDef).hasClass('manager-on') || $(_this.option.isDef).hasClass('skin-check')) {
      isDefault = 1;
    }

    var url = siteUrl + '/address/save_address';
    $.post(url, {id:type, 'receiver': receiver, 'address': address, 'mobile': mobile, 'telphone': tel, 'is_default': isDefault, 'province': prov, 'city': city, 'district': dist}, function (json) {
      if (json.info == 'ok') {
        $(_this.option.input).val(json.id);
        // 展示信息
        _this.hideForm();

        $(_this.option.infoDiv).find('.name').html(receiver);
        if (mobile) {
          $(_this.option.infoDiv).find('.tel').html(mobile);
        } else {
          $(_this.option.infoDiv).find('.tel').html(tel);
        }
        if ($(_this.option.infoDiv).find('.address-detail')) {
          $(_this.option.infoDiv).find('.address-detail').html(address);
          $(_this.option.infoDiv).find('.address').html(provT + ' ' + cityT + ' ' + distT);
        } else {
          $(_this.option.infoDiv).find('.address').html(provT + ' ' + cityT + ' ' + distT + ' ' + address);
        }

        var info = provT+' '+cityT+' '+distT+' '+address+' （'+receiver+'收） '+mobile;
        _this.setInfo(type, json.id, info, receiver, address, mobile, provT, cityT, distT);
        $(_this.option.save).data('saving', 0);
      } else {
        showMsg(json.info, 'error');
        $(_this.option.save).data('saving', 0);
      }
    }, 'json');
  }

  AddressJs.prototype.setInfo = function(type, id, info, receiver, address, mobile, provT, cityT, distT)
  {
    var _this = this;
    if (type == 'new') {
      $(this.option.listDiv).find('li').removeClass('curr');
      $(this.option.listDiv).find('.radio-bg').removeClass('checked');
      $(this.option.listDiv).find('input').attr('checked', false);
      $(this.option.listDiv).prepend('<li class="curr" data-address_id="' + id + '"><label><i class="radio-bg checked"></i><input type="radio js_sltAddress" value="'+id+'" class="radio1">' + info + '</label><span data-type="child" data-address_id="'+id+'">编辑</span></li>');
      $(this.option.parentDiv).attr('data-address_id', id);
      if (this.option.paydiv) {
        $(this.option.paydiv).addClass('hidden');
        $(this.option.sltPayDiv).removeClass('hidden');
      }
    } else {
      $(this.option.listDiv).find('li').each(function() {
        if ($(this).attr('data-address_id') == id) {
          console.log(111);
          $(this).html('<label><i class="radio-bg checked"></i><input type="radio js_sltAddress" value="'+id+'" class="radio1">' + info + '</label><span data-type="child" data-address_id="'+id+'">编辑</span>');
          _this.sltChange($(this));
        }
      });
      $(_this.option.parentDiv).attr('data-address_id', id);
    }

    $(_this.option.parentDiv).attr('data-edit-address', 0);
  }

  // 删除提示信息
  AddressJs.prototype.deleteMsg = function(obj){
    obj.parent().removeClass('error');
    obj.closest('p').find('.prompt').remove();
  }
  // 提示信息
  AddressJs.prototype.inputMsg =  function(obj, msg) {
    obj.parent().addClass('error');
    obj.closest('p').append('<span class="prompt"><i class="false-icon"></i>' + msg + '</span>');
  }

  window.AddressJs = AddressJs;
})();